<?php
namespace app\middleware;

class Validate
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle( $request, \Closure $next )
    {
        //获取当前参数
        $param = $request->param();

        //获取控制器
        $controller = $request->controller();

        //获取行为
        $action = $request->action();

        //自动验证器名
        $validate_class = 'app\\validate\\' . str_replace( '.', '\\', $controller );

        //存在验证器则自动验证
        if( class_exists( $validate_class ) )
        {
            $validate = new $validate_class;
            //验证场景
            if( $validate->hasScene( $action ) )
            {
                $validate->scene( $action );

                if( ! $validate->check( $param ) )
                {
                    return json( [ 'code' => '10001', 'message' => 'error data', 'data' => $validate->getError() ] );
                }
            }
        }

        return $next( $request );
    }
}
